/*******************************************************************************
 * Copyright 2011 WaTho
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.wathoserver.android.dragoid.util;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import de.wathoserver.android.dragoid.api.DragoStore;
import de.wathoserver.android.dragoid.api.DragoidConstants;

/**
 * Task ruft asynchron eine Methode auf und zeigt Fortschrittsdialog und
 * Fehlermeldungen dazu an.
 * 
 * @author watho
 * 
 * @param <T>
 *            Typ der aufzurufenden Daten
 */
public class UrlParsingTask<T> extends AsyncTask<Void, Void, Boolean> {

	private T data;
	private UrlParsingActivity<T> activity;
	private Activity context;

	public UrlParsingTask(Activity context, UrlParsingActivity<T> activity) {
		this.context = context;
		this.activity = activity;
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		try {
			data = activity.fetchData();
			return true;
		} catch (IllegalAccessException e) {
			Log.e(DragoidConstants.LOG_TAG, "Fehler beim Parsen des HTML", e);
		} catch (IllegalStateException e){
			Log.e(DragoidConstants.LOG_TAG, "Fehler beim Parsen des HTML", e);
		}
		return false;
	}

	@Override
	protected void onPreExecute() {
		context.showDialog(UrlParsingActivity.DIALOG_PROGRESS);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		context.dismissDialog(UrlParsingActivity.DIALOG_PROGRESS);
		if (result) {
			DragoStore.getDragoStore().getUserInfo()
					.updateUI(activity.getUserInfoActivity());
			activity.onSuccess(data);
		} else {
			Toast.makeText(context,
					"Beim Parsen der Seite ist etwas schiefgegegangen.",
					Toast.LENGTH_LONG).show();
		}
	}

}
